package com.rytong.tools.ui;

import java.util.Vector;
import com.rytong.tools.utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.TextView;

public class LPLabel extends Component {

    private boolean isHyperLink_;
    private String linkedUri_;
    private boolean isSingleLine_;
    boolean focus_;

    // just use for parse.
    public boolean isTagParse_ = false;

    /**
     * when it is true, its attrName_/attrValue_ will be use to transfer parameters to the server
     */
    public boolean isValueLabel_ = false;

    // Roll always without no stopping
    boolean isRollNotStop;

    /** delay time */
    private int delaytime_;
    int textColor_;
    /** count down */
    boolean isCountDown_;
    /***/
    private String[] relaDismiss_;
    /***/
    private String[] relaUnfocusable_;
    String labelName_;

    protected boolean isClicked_ = false;
    protected int clickedColor_;
    private final int FONTPADDING = 2;
    Bitmap bs;
    String textAlign_;
    
    //字体属性
    private int mFontSize = 0;
    private boolean mFontWeight = false;
    
    // 如果这个label带有rectcolor属性，那么需要在前面绘制一个矩形色块，这是矩形色块的宽度。
    public static final int RECT_WIDTH_ = Utils.getScaledValueX(30);
    // 需要绘制的色块的颜色。
    private int rectColor_ = -1;
    
    // indicate that the label should be wrapped to multi-lines.
    // private boolean isLineFeed_;
    
    /**
     * @author Chris
     * 
     */
    public class MyLPLabel extends TextView implements CompositedComponent {

        public MyLPLabel(Context context, String text) {
            super(context);
            boolean isFocusable = focusable();
            setFocusable(isFocusable);
            setFocusableInTouchMode(isFocusable);
            setText(text);
        }

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
                break;
            default:
                return super.onKeyDown(keyCode, event);
            }
            return true;
        }

        @Override
        public boolean onKeyUp(int keyCode, KeyEvent event) {
            boolean isAction = false;
            switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
                // bv.setCurrentItem(bv.tabBar_.indexOfContentChild(this));
                break;
            default:
                isAction = super.onKeyDown(keyCode, event);
            }
            return isAction;
        }
        
        @Override
        protected void onDraw(Canvas canvas) {
        	int rectWidth = (rectColor_ == -1) ? 0 : LPLabel.RECT_WIDTH_;
        	int oldPaintColor = -1;
        	if (getPropertyByName("loop").toString().equalsIgnoreCase("true")) {
        		drawMoveStr(this, canvas, getWidth(), getPaint(), (String) getText(), 0,
    					((int) (getHeight() + getPaint().getTextSize())) >> 1);
        	} else if (getPropertyByName("lineNumber").toString().equalsIgnoreCase("1")) {
        		String text = (String) getText();
        		Vector stringArr = new Vector();
        		paint_ = getPaint();
        		oldPaintColor = paint_.getColor();
        		if (paint_.measureText(text) > width_) {
        			int i = text.length();
        			while (paint_.measureText(text.substring(0, i)) > width_) {
        				i = i - 1;
        			}
        			String text1 = text.substring(0, i);
        			String text2 = text.substring(i, text.length());
        			if (text2 != null && !text2.equals("") && text2.length() > 0) {
        				stringArr.add(text1.substring(0, text1.length() - 1).concat("..."));
        			} else {
        				stringArr.add(text1);
        			}
        		} else {
        			stringArr.add(text);
        		}
        		int text_height = ((int) (paint_.getTextSize() * 3)) >> 2;
        		
        		int length = stringArr.size();
        		if (length == 1) {
        			blankY_ = 0;
        			text_height = ((text_height + getHeight()) >> 1);
        		}
        		float coordinate_y = Utils.getScaledValueY(blankY_) + text_height;
        		// 画一个矩形。
        		if(rectWidth > 0){
        			paint_.setColor(rectColor_);
        			canvas.drawRect(0, (text_height + Utils.getScaledValueY(SPACE_Y_) - rectWidth / 2) / 2, rectWidth, 
        					(text_height + Utils.getScaledValueY(SPACE_Y_) - rectWidth / 2) / 2 + rectWidth / 2, paint_);
        			paint_.setColor(oldPaintColor);
        		}
        		for (int i = 0; i < length; i++) {
        			if(stringArr.elementAt(i) != null){
        				if (i > 0){
        					coordinate_y += text_height + Utils.getScaledValueY(SPACE_Y_);
        				}
        				canvas.drawText((String) stringArr.elementAt(i), rectWidth, coordinate_y, paint_);
        			}
        		}
        	} else if (getPropertyByName("lineNumber").toString().equalsIgnoreCase("2")) {
        		String text = (String) getText();
        		Vector stringArr = new Vector();
        		paint_ = getPaint();
        		oldPaintColor = paint_.getColor();
        		if (paint_.measureText(text) > width_) {
        			int i = text.length();
        			while (paint_.measureText(text.substring(0, i)) > width_) {
        				i = i - 1;
        			}
        			stringArr.add(text.substring(0, i));
        			stringArr.add(text.substring(i, text.length()));
        			
        			String text2 = (String) stringArr.elementAt(1);
        			if (paint_.measureText(text2) > width_) {
        				int j = text2.length();
        				while (paint_.measureText(text2.substring(0, j)) > width_) {
        					j = j - 1;
        				}
        				stringArr.removeElementAt(1);
        				stringArr.add(text2.substring(0, j - 1).concat("..."));
        			}
        		} else {
        			stringArr.add(text);
        		}
        		
        		int text_height = ((int) (paint_.getTextSize() * 3)) >> 2;
        		int length = stringArr.size();
        		if (length == 0)
        			return;
        		int textValign_x = 0;
        		float coordinate_y = 0;
        		if (getPropertyByName("valign").toString().equalsIgnoreCase("middle")) {
        			textValign_x = (height_ - Utils.getScaledValueY(SPACE_Y_) * (length - 1) - text_height * length) / 2;
        			if (textValign_x < 0)
        				textValign_x = 0;
        			coordinate_y = text_height + textValign_x;
        		} else
        			coordinate_y = Utils.getScaledValueY(blankY_) + text_height;
        		// 画一个矩形。
        		if(rectWidth > 0){
        			paint_.setColor(rectColor_);
        			canvas.drawRect(0, (text_height + Utils.getScaledValueY(SPACE_Y_) - rectWidth / 2) / 2, rectWidth, 
        					(text_height + Utils.getScaledValueY(SPACE_Y_) - rectWidth / 2) / 2 + rectWidth / 2, paint_);
        			paint_.setColor(oldPaintColor);
        		}
        		for (int i = 0; i < length; i++) {
        			if(stringArr.elementAt(i) != null){
        				if (i > 0)
        					coordinate_y += text_height + Utils.getScaledValueY(SPACE_Y_);
        				canvas.drawText((String)stringArr.elementAt(i), rectWidth, coordinate_y, paint_);
        			}
        		}
//            } else if(Gravity.LEFT != getGravity()){ 
//                
//                //弥补下面文本
//                super.onDraw(canvas);
        	}else {
        		// super.onDraw(canvas);
        		// 下面手动绘制label上的文字，不再调用系统的方法了
        		paint_ = getPaint();
        		oldPaintColor = paint_.getColor();
        		//设置字体大小
        		if(mFontSize > 0){
        			paint_.setTextSize(mFontSize);
        		}
        		paint_.setFakeBoldText(mFontWeight);
        		
        		// int text_height = (int) paint_.getTextSize();// 文字高度
        		int text_height = ((int) (paint_.getTextSize() * 3)) >> 2;
        		if (null == stringArr_) {
        			return;
        		}
        		int length = stringArr_.length;
        		if (length == 1) {
        			blankY_ = 0;
        			text_height = ((text_height + getHeight()) >> 1);
        		}
        		// 取后台给的宽度值，如果给了宽度值则textAlign_相对于label本身有效果
        		String w = "";
        		if (null != cssStyle_)
        			w = cssStyle_.getProperty(CssStyle.WIDTH);
        		// 初始高度为留白高+字高
        		float coordinate_y = Utils.getScaledValueY(blankY_) + text_height;
        		// 画一个矩形。
        		if(rectWidth > 0){
        			paint_.setColor(rectColor_);
        			canvas.drawRect(0, (text_height + Utils.getScaledValueY(SPACE_Y_) - rectWidth / 2) / 2, rectWidth, 
        					(text_height + Utils.getScaledValueY(SPACE_Y_) - rectWidth / 2) / 2 + rectWidth / 2, paint_);
        			paint_.setColor(oldPaintColor);
        		}
        		/**
        		 * 绘制两行以上的多行文字的时候，要加入字间距。
        		 */
        		float charPadding = 0; // 字间距。
        		if(pos_ == null){ // 只初始化一次字间距数组。
        			pos_ = new float[length][]; // 初始化行。
        			for (int i = 0; i < length; i++) {
        				// 初始化字间距。
        				if(stringArr_[i].endsWith("\n")){
        					String lineString = stringArr_[i].substring(0, stringArr_[i].lastIndexOf("\n"));
            				charPadding = (maxLineWidth_ - 
            						paint_.measureText(lineString)) / (lineString.length() - 1);
            				pos_[i] = new float[lineString.length() * 2]; // 初始化一行当中的字符间距。
            			} else {
            				charPadding = (maxLineWidth_ - 
            						paint_.measureText(stringArr_[i])) / (stringArr_[i].length() - 1);
            				pos_[i] = new float[stringArr_[i].length() * 2]; // 初始化一行当中的字符间距。
            			}
            			if(i == length - 1 || stringArr_[i].endsWith("\n")){ // 最后一行和自然段尾行不计算字间距。
            				charPadding = 0;
            			}
            			// 初始化纵向坐标。
            			if (i > 0)
        					coordinate_y += text_height + Utils.getScaledValueY(SPACE_Y_);
            			// 初始化横向坐标。
            			int x = 0;
            			if (null != w && !w.equals("") && textAlign_ != null && textAlign_.equals("center")) {
        					x = (width_ - ((int) (maxLineWidth_) + 1)) >> 1;
            			} else if (null != w && !w.equals("") && textAlign_ != null && textAlign_.equals("right")) {
        					x = width_ - ((int) (maxLineWidth_) + 5);
            			} else {
            				x = 0;
            			}
            			x = Math.max(0, x); // x的最小值为0。
            			// 计算字符间距数组的值。
    					for (int j = 0; j < pos_[i].length; j++) {
							if(j == 0){
								pos_[i][j] = x + rectWidth;
							} else if(j % 2 == 0){
								pos_[i][j] = x + rectWidth + charPadding * (j >> 1)
										+ paint_.measureText(stringArr_[i].substring(0, (j >> 1)));
							} else {
								pos_[i][j] = coordinate_y;
							}
						}
					}
        		}
        		// 画字符串。
        		for (int i = 0; i < length; i++) {
        			if(stringArr_[i] != null && pos_ != null){
        				if(stringArr_[i].endsWith("\n")){ // 不画换行符。
        					canvas.drawPosText(stringArr_[i].substring(0, stringArr_[i].lastIndexOf("\n")),
        							pos_[i], paint_);
        				} else {
        					canvas.drawPosText(stringArr_[i], pos_[i], paint_);
        				}
        			}
        		}
        	}
        }
        
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            boolean isAction = false;
            int touchEvent = event.getAction();
            switch (touchEvent) {
            case MotionEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
                xDown_ = event.getX();
                yDown_ = event.getY();
                this.requestFocus();
                isAction = true;
                break;
            case MotionEvent.ACTION_MOVE:
            	// 移动tr恢复颜色。
            	int offset = (int) Math.abs(yDown_ - event.getY());
            	if (offset > offset_) {
            		trMoveColor(tr_, llvSV_);
            	}
                moveY(yDown_, event.getY());
                break;
            case MotionEvent.ACTION_UP:
            	// 抬起tr恢复颜色。
            	trUpColor(tr_, llvSV_);
                xUp_ = (int) event.getX();
                yUp_ = (int) event.getY();
                if (Math.abs(xUp_ - xDown_) > offset_ || Math.abs(yUp_ - yDown_) > offset_) {
                    return false;
                }
                isAction = onClick((String) composited().property_.get("onclick"));
                break;
            default:
                isAction = super.onTouchEvent(event);
            }

            return isAction;
        }

        public Component composited() {
            // TODO Auto-generated method stub
            return LPLabel.this;
        }
    }
    

    /**
     * @param text
     * @return
     */
    private int getCFNumber(String text) {
        int count = -1;
        int index = -1;
        int lastIndex = 0;
        do {
            index = text.indexOf('\n', lastIndex);
            lastIndex = index + 1;
            count++;
        } while (index > 0);

        return count;
    }

    /*
     * ************************************************************************
     * Set and Get methods. ************************************************************************
     */
    /**
     * @param linkUri
     *            the linkAddr_ to set
     */
    public void setLinkedUri(String linkUri) {
        linkedUri_ = linkUri;
    }

    /**
     * @return the linkAddr_
     */
    public String linkedUri() {
        return linkedUri_;
    }

    /**
     * @param delaytime
     *            the delaytime_ to set
     */
    public void setDelaytime(int delaytime) {
        delaytime_ = delaytime;
    }

    /**
     * @return the delaytime_
     */
    public int delaytime() {
        return delaytime_;
    }

    /**
     * @param isHyperLink
     *            the isHyperLink_ to set
     */
    public void setHyperLink(boolean isHyperLink) {
        isHyperLink_ = isHyperLink;
    }

    /**
     * @return the isHyperLink_
     */
    public boolean isHyperLink() {
        return isHyperLink_;
    }

    /**
     * @param relaDismiss_
     *            the relaDismiss_ to set
     */
    public void setRelaDismiss(String[] relaDismiss_) {
        this.relaDismiss_ = relaDismiss_;
    }

    /**
     * @return the relaDismiss_
     */
    public String[] relaDismiss_() {
        return relaDismiss_;
    }

    /**
     * @param relaUnfocusable_
     *            the relaUnfocusable_ to set
     */
    public void setRelaUnfocusable(String[] relaUnfocusable_) {
        this.relaUnfocusable_ = relaUnfocusable_;
    }

    /**
     * @return the relaUnfocusable_
     */
    public String[] relaUnfocusable() {
        return relaUnfocusable_;
    }

    /**
     * 
     * 设置label控件的文字对齐方式，该效果当label控件未重写ondraw方法时有�
     * 
     * 
     * 
     * @param index
     */

    public void setGravity(int index) {

        if (realView_ != null) {

            MyLPLabel label = (MyLPLabel) realView_;

            label.setGravity(index);

        }

    }

    public void setTextColor(int color) {

        if (realView_ != null) {

            MyLPLabel label = (MyLPLabel) realView_;

            label.setTextColor(color);

        }

    }

    @Override
    public void setContentText(String text) {
        super.setContentText(text);
        if (realView_ != null) {
            try {
                MyLPLabel label = (MyLPLabel) realView_;
                label.setText(text);
            } catch (Exception e) {
                Utils.printException(e);
            }
        }
    }

    /**
     * 该方法主要用于指定控件的大小\显示颜色\样式�如果服务端没有给定输出样式大� 则要自行计算一个合适的大小应用于该控件 Mould this component with its shape, color, size and
     * so on.
     * 
     * @return
     * @throws Exception
     *             TODO
     */
    public void mouldH() throws Exception {
        super.mouldH();
        reSetTextViewLayoutParams();
        // 登记这个矩形色块的颜色。
        String rectColorStr = getPropertyByName("rectcolor");
        if(rectColorStr != null && !"".equals(rectColorStr)){
        	try{
        		rectColor_ = Color.parseColor(rectColorStr);
        	} catch (Exception e) {}
        }
        if (cssStyle_ != null) {
        	textAlign_ = cssStyle_.getProperty(CssStyle.TEXTALIGN);
        	mouldCssStyle();
        }
    }
    
    @Override
    public void mouldCssStyleByName(String name, String value) {
        super.mouldCssStyleByName(name,value);

        if (TextUtils.isEmpty(value)) {

            return;
        }

        if (name.equalsIgnoreCase(CssStyle.TEXTALIGN)) {

            textAlign_ = value;
        } else if (name.equalsIgnoreCase(CssStyle.FONTSIZE)) {

            int fontSize = Integer.parseInt(fixedPX(value));
            fontSize = Utils.getFontSize(fontSize);
            if (fontSize > 0) {

                mFontSize = fontSize;
            }
        } else if (name.equalsIgnoreCase(CssStyle.FONTWEIGHT)) {

            mFontWeight = value.equalsIgnoreCase("bold") ? true : false;
        } 
        invalidate();
    }

    public void mouldCssStyle() {
        try {
            // TODO Auto-generated method stub
            super.mouldCssStyle();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    @Override
    public void initRealView(Activity activity, String value) {
        // TODO Auto-generated method stub
        realView_ = new MyLPLabel(activity, value);
        super.initRealView(activity, value);
    }
    
    @Override
    public void releaseResource(Component component) {
    	// TODO Auto-generated method stub
    	super.releaseResource(component);
    	Utils.releaseObject(relaDismiss_);
    	Utils.releaseObject(relaUnfocusable_);
    	Utils.releaseObject(bs);
    }

}
